<template>
  <div class="pad-20 bgc-default">
    <div class="pad-b-20">
      <div class="flex-left">
        <div class="panel" v-if="!isShowOtherPromotion">
          <div class="height-98 flex-left pad-l-20 pad-r-20">
            <img :src="limitedTime" alt="" class="width-66 height-66">
            <div class="mar-l-20 height-90 flex-item">
              <div class="mar-t-23">
                <div class="font-18">社区团购</div>
                <div class="font-14 font-color-6 mar-t-5 line-x">创建团购活动今日下单次日达</div>
              </div>
            </div>
          </div>
          <div class="manage-row flex-center height-51">
            <div class="createBtn seckillBtn" @click="handleCreate(2)">立即创建</div>
          </div>
        </div>
        <div class="panel" v-if="isShowOtherPromotion">
          <div class="height-98 flex-left pad-l-20 pad-r-20">
            <img :src="limitedTime" alt="" class="width-66 height-66">
            <div class="mar-l-20 height-90 flex-item">
              <div class="mar-t-23">
                <div class="font-18">限时秒杀</div>
                <div class="font-14 font-color-6 mar-t-5 line-x">限时抢购引导客户更多消费</div>
              </div>
            </div>
          </div>
          <div class="manage-row flex-center height-51">
            <div class="createBtn seckillBtn" @click="handleCreate(0)">立即创建</div>
            <!-- <div class="width-1 height-36 bg-color-white"></div>
            <div class="width-150 height-46 flex-center" @click="clickActivityType('0')">管理</div> -->
          </div>
        </div>
        <div class="panel" v-if="this.getVersionType() !== '5' && isShowOtherPromotion">
          <div class="height-98 flex-left pad-l-20 pad-r-20">
            <img :src="freeShipping" alt="" class="width-66 height-66">
            <div class="mar-l-20 height-90 flex-item">
              <div class="mar-t-23">
                <div class="font-18">满额包邮</div>
                <div class="font-14 font-color-6 mar-t-5 line-x">满足消费一定金额时对指定商品免邮费</div>
              </div>
            </div>
          </div>
          <div class="manage-row flex-center height-51">
            <div class="createBtn postBtn" @click="handleCreate(1)">立即创建</div>
            <!-- <div class="width-1 height-36 bg-color-white"></div>
            <div class="width-150 height-46 flex-center" @click="clickActivityType('1')">管理</div> -->
          </div>
        </div>
      </div>
    </div>
    <div class="pad-l-20 pad-r-20 bg-color-white">
      <div class="tab-style-default">
        <el-tabs v-model="promotionStatus" @tab-click="statusClick">
          <el-tab-pane label="全部" name="4"></el-tab-pane>
          <el-tab-pane label="待发布" name="0"> </el-tab-pane>
          <el-tab-pane label="待开始" name="1"> </el-tab-pane>
          <el-tab-pane label="进行中" name="2"> </el-tab-pane>
          <el-tab-pane label="已结束" name="3"> </el-tab-pane>
        </el-tabs>
      </div>
      <div class="top-operate">
        <div>
          <div class="float-l">
            <span>搜索活动：</span>
            <el-input @keyup.enter.native="handleSearch" v-model="dataListQuery.keyword" placeholder="活动名称"
              style="width: 300px"></el-input>
            <span class="pad-l-20" v-if="isShowOtherPromotion">活动类型：</span>
            <el-select class="select-class mar-l-10" v-model="activityType" style="width: 120px"
              v-if="isShowOtherPromotion">
              <el-option label="全部类型 " value="-1"></el-option>
              <el-option label="秒杀" value="0"></el-option>
              <el-option label="包邮" value="1"></el-option>
            </el-select>
            <span class="pad-l-20">活动时间：</span>
            <el-date-picker class="mar-l-10" v-model="dataListQuery.promotionStartTime"
              value-format="yyyy-MM-dd HH:mm:ss" type="date" default-time="00:00:00" placeholder="开始日期">
            </el-date-picker> -
            <el-date-picker v-model="dataListQuery.promotionEndTime" value-format="yyyy-MM-dd HH:mm:ss" type="date"
              default-time="23:59:59" placeholder="结束日期">
            </el-date-picker>
            <el-button class="mar-l-10" type="primary" @click="handleSearch">查询</el-button>
            <el-button style="margin-left: 10px;" plain="" @click="resetSearch">重置</el-button>
            <el-button class="mar-l-10" type="primary" v-if="!isShowOtherPromotion" @click="setGroupBuyCutOffOrderTime">
              设置截单时间
            </el-button>
          </div>
          <br>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table :data="dataList" @selection-change="handleSelectionChange" v-loading="listLoading"
          element-loading-text="加载中" style="width: 100%;" header-cell-class-name="default-header"
          row-class-name="default-row">
          <el-table-column min-width="240px" label="活动标题" fixed="left">
            <template slot-scope="scope">
              <span @click="handleUpdate(scope.row, 0)" class="cursor-p">{{scope.row.title}}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="180px" label="活动类型">
            <template slot-scope="scope">
              <span v-if="scope.row.activityType == 0">秒杀</span>
              <span v-if="scope.row.activityType == 1">包邮</span>
              <span v-if="scope.row.activityType == 2">社区团购</span>
            </template>
          </el-table-column>
          <el-table-column min-width="200px" label="活动时间">
            <template slot-scope="scope" v-if="scope.row.startTime && scope.row.endTime">
              开始：{{scope.row.startTime}}<br>
              结束：{{scope.row.endTime}}
            </template>
          </el-table-column>
          <el-table-column min-width="200px" label="停止时间" prop="stopTime"></el-table-column>
          <el-table-column min-width="200px" label="状态" prop="promotionStatus">
            <template slot-scope="scope">
              <span v-if="scope.row.promotionStatus == 0">待发布</span>
              <span type="warning" v-if="scope.row.promotionStatus == 1">待开始</span>
              <span type="success" v-if="scope.row.promotionStatus == 2">进行中</span>
              <span type="danger" v-if="scope.row.promotionStatus == 3">
                <span v-if="scope.row.stopType == 1">手动停止</span>
                <span v-else>已停止</span>
              </span>
            </template>
          </el-table-column>
          <el-table-column width="160px" label="操作" align="right" fixed="right">
            <template slot-scope="scope">
              <div>
                <el-button type="text" size="medium" v-if="scope.row.promotionStatus == 0"
                  @click="releasePromotion(scope.row)">发布</el-button>
                <el-button type="text" size="medium" v-if="scope.row.promotionStatus != 0"
                  @click="handleUpdate(scope.row, 0)">查看</el-button>
                <el-button type="text" size="medium" v-if="scope.row.promotionStatus == 0"
                  @click="handleUpdate(scope.row, 1)">编辑</el-button>
                <!--<el-button type="primary" v-if="scope.row.promotionStatus == 0 || scope.row.promotionStatus == 1" @click="handleUpdate(scope.row, 'copy')">复制</el-button>-->
                <el-button type="text" size="medium" plain
                  v-if="scope.row.promotionStatus == 2 || scope.row.promotionStatus == 1 || scope.row.promotionStatus == 0"
                  @click="handleChangeStatus(scope.row)">停止</el-button>
                <el-button type="text" size="medium" v-if="scope.row.promotionStatus == 3"
                  @click="handleData(scope.row)">数据</el-button>
                <el-popover placement="bottom" width="100" trigger="hover" popper-class="popover-class"
                  v-if="scope.row.promotionStatus == 3">
                  <el-button class="mar-l-10" type="text" size="medium" slot="reference">更多
                  </el-button>
                  <el-button type="text" size="medium"
                    v-if="scope.row.promotionStatus != 1 && scope.row.promotionStatus != 2"
                    @click="deletePromotion(scope.row)">删除</el-button>
                  <el-button type="text" size="medium" v-if="!isShowOtherPromotion"
                    @click="showCusOrderList(scope.row)">顾客订单</el-button>
                  <el-button type="text" size="medium" v-if="!isShowOtherPromotion"
                    @click="showDeliveryOrderList(scope.row)">团长配送单</el-button>
                </el-popover>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="dataListQuery.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="dataListQuery.size"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
      <div v-if="!isShowOtherPromotion">
        <el-dialog width="700px" title="截单时间设置" :visible.sync="isShowSetGroupBuyCutOffOrderTimeDialog">
          <el-form :model="groupBuyCutOffOrderTimeForm" label-width="100px" ref="groupBuyCutOffOrderTimeForm"
            :rules="groupBuyCutOffOrderTimeRule">
            <el-form-item class="mar-l-20" label="截单时间:" prop="statTime">
              <el-time-picker v-model="groupBuyCutOffOrderTimeForm.statTime" value-format='HH:mm:ss' format='HH:mm:ss'
                :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" placeholder="截单时间">
              </el-time-picker>
            </el-form-item>
            <el-form-item class="mar-l-20" label="截单周期:" prop="orderStatTimeWeekCycle">
              <el-checkbox-group v-model="groupBuyCutOffOrderTimeForm.orderStatTimeWeekCycle">
                <el-checkbox-button v-for="week in weekList" :label="week" :key="week">{{week}}
                </el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShowSetGroupBuyCutOffOrderTimeDialog = false">取消</el-button>
            <el-button type="primary" @click="saveGroupBuyCutOffOrderTimeConfig">确定</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    pagingPromotion,
    updatePromotionStatus,
    deletePromotion,
    updatePromoitonRelease
  } from '@/api/sell/promotion'
  import {
    getByEnterpriseId,
    saveOrderStatTimeInfo
  } from '@/api/user/enterprise'
  import limitedTime from '@/assets/images/limited-time.png'
  import freeShipping from '@/assets/images/free-shipping.png'
  export default {
    props: {
      promotionType: {
        type: Number,
        default: 0
      }
    },
    computed: {
      isShowOtherPromotion() {
        return this.promotionType !== 2
      }
    },
    data() {
      return {
        total: null,
        dataList: [],
        listLoading: true,
        promotionStatus: '4',
        activityType: '-1',
        dataListQuery: {
          keyword: '',
          userType: '1',
          userId: this.getEnterpriseId(),
          promotionStartTime: '',
          promotionEndTime: '',
          currentPage: 1,
          size: 10
        },
        dict: {},
        limitedTime: limitedTime,
        freeShipping: freeShipping,
        isShowSetGroupBuyCutOffOrderTimeDialog: false,
        groupBuyCutOffOrderTimeForm: {
          statTime: this.getDefaultStatTime(),
          timeCol: 'payTime',
          textCol: 'goodsTitle',
          textValue: '',
          orderStatTimeWeekCycle: []
        },

        weekList: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        groupBuyCutOffOrderTimeRule: {
          statTime: [{
            required: true,
            message: '截单时间不能为空',
            trigger: 'blur'
          }],
          orderStatTimeWeekCycle: [{
            required: true,
            message: '截单周期不能为空',
            trigger: 'blur'
          }]
        },
        enterpriseConfig: {}
      }
    },
    // 初始化页面
    created() {
      // 当前页面的业务类型为社区团购类型的时候 不显示其它活动入口
      if (this.promotionType === 2) {
        this.activityType = this.promotionType
      }
      this.getGroupBuyCutOffOrderTimeConfig()
    },
    mounted() {
      const queryParams = this.getCurrentPage().query
      console.log(queryParams)
      console.log(queryParams.activityType)
      if (queryParams.activityType) {
        this.activityType = queryParams.activityType + ''
      }
      this.listLoading = false
      this.initData()
    },
    methods: {
      // 添加
      handleCreate(activityType) {
        // 秒杀
        if (activityType === 0) {
          this.$router.push({
            path: '/sell-promotion/list-promotion/edit/index',
            query: {
              activityType: activityType
            }
          })
        }
        // 包邮
        if (activityType === 1) {
          this.$router.push({
            path: '/sell-promotion/list-promotion/edit-fee/index',
            query: {
              activityType: activityType
            }
          })
        }
        // 包邮
        if (activityType === 2) {
          this.$router.push({
            path: '/sell-promotion/list-promotion/edit-group-buy/index',
            query: {
              activityType: activityType
            }
          })
        }
      },
      clickActivityType(activityType) {
        this.$router.push({
          path: '/sell-promotion/list-promotion/index',
          query: {
            activityType: activityType
          }
        })
      },
      initData() {
        this.listLoading = true
        if (this.promotionStatus === '4') {
          this.dataListQuery['promotionStatus'] = ''
        } else {
          this.dataListQuery['promotionStatus'] = this.promotionStatus
        }
        if (this.activityType === '-1') {
          this.dataListQuery['activityType'] = ''
          // 排除社区团购活动 社区团购活动单独列表显示
          this.dataListQuery['activityTypeList'] = '0,1'
        } else {
          this.dataListQuery['activityType'] = this.activityType
        }
        pagingPromotion(this.dataListQuery).then(response => {
          this.dataList = response.data.records
          this.total = response.data.total
          this.listLoading = false
          this.dict = response.data.dict
        })
      },
      resetSearch() {
        this.dataListQuery.keyword = ''
        this.dataListQuery.promotionStartTime = ''
        this.dataListQuery.promotionEndTime = ''
        this.promotionStatus = '4'
        if (this.activityType !== 2) {
          this.activityType = '-1'
        }
        this.initData()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.dataListQuery.size = val
        this.initData()
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.dataListQuery.currentPage = val
        this.initData()
      },
      // 勾选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      statusClick() {
        this.dataListQuery.currentPage = 1
        this.dataListQuery.keyword = ''
        this.dataListQuery.promotionStartTime = ''
        this.dataListQuery.promotionEndTime = ''
        this.initData()
      },
      // 查询
      handleSearch() {
        this.dataListQuery.currentPage = 1
        this.initData()
      },
      deletePromotion(row) {
        const data = {
          promotionId: row.promotionId
        }
        this.$confirm('此操作将删除该数据，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deletePromotion(data).then(response => {
            if (response.isError) return
            this.initData()
          })
        }).catch(() => {})
      },
      copyPromotion(row) {

      },
      handleChangeStatus(row) {
        const data = {
          promotionId: row.promotionId,
          promotionStatus: '3',
          stopType: 1
        }
        this.$confirm('此操作将结束该活动，是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updatePromotionStatus(data).then(response => {
            if (response.isError) return
            this.initData()
          })
        })
      },
      releasePromotion(row) {
        this.$confirm('是否确认发布?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updatePromoitonRelease(row.promotionId).then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '成功!'
            })
            this.initData()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
      },
      handleData(row) {
        if (row.activityType === 0) {
          this.$router.push({
            path: '/sell-promotion/list-promotion/detail-data/index',
            query: {
              promotionId: row.promotionId
            }
          })
        }
        if (row.activityType === 1) {
          this.$router.push({
            path: '/sell-promotion/list-promotion/detail-data-fee/index',
            query: {
              promotionId: row.promotionId
            }
          })
        }
        if (row.activityType === 2) {
          // 路由指向页面实际公用list-promotion/detail-data/index页面
          this.$router.push({
            path: '/sell-promotion/list-promotion/detail-data-group-buy/index',
            query: {
              promotionId: row.promotionId
            }
          })
        }
      },
      // 编辑
      handleUpdate(row, status) {
        // 清除赋值
        const promotionId = row.promotionId
        let disabledBoolean = false
        if (status === 0) {
          disabledBoolean = true
        }
        // 秒杀
        if (row.activityType === 0) {
          if (status === 'copy') {
            this.$router.push({
              path: '/sell-promotion/list-promotion/edit/index',
              query: {
                promotionId: promotionId,
                activityType: row.activityType.toString(),
                disabledBoolean: disabledBoolean,
                copyBoolean: true
              }
            })
          }
          this.$router.push({
            path: '/sell-promotion/list-promotion/edit/index',
            query: {
              promotionId: promotionId,
              activityType: row.activityType.toString(),
              disabledBoolean: disabledBoolean,
              copyBoolean: false
            }
          })
        }
        if (row.activityType === 1) {
          this.$router.push({
            path: '/sell-promotion/list-promotion/edit-fee/index',
            query: {
              promotionId: promotionId,
              activityType: row.activityType.toString(),
              disabledBoolean: disabledBoolean
            }
          })
        }
        if (row.activityType === 2) {
          this.$router.push({
            path: '/sell-promotion/list-promotion/edit-group-buy/index',
            query: {
              promotionId: promotionId,
              activityType: row.activityType.toString(),
              disabledBoolean: disabledBoolean
            }
          })
        }
      },
      showCusOrderList(row) {
        this.$router.push({
          path: '/community/order/index',
          query: {
            promotionId: row.promotionId
          }
        })
      },
      showDeliveryOrderList(row) {
        this.$router.push({
          path: '/community/order/delivery/index',
          query: {
            promotionId: row.promotionId
          }
        })
      },
      getDefaultStatTime() {
        // const statTime = new Date()
        // statTime.setHours(21)
        // statTime.setMinutes(0)
        // statTime.setSeconds(0)
        return '21:00:00'
      },
      setGroupBuyCutOffOrderTime() {
        this.isShowSetGroupBuyCutOffOrderTimeDialog = true
      },
      getGroupBuyCutOffOrderTimeConfig() {
        const that = this
        getByEnterpriseId(this.getEnterpriseId()).then(response => {
          if (response.isError) return
          that.enterpriseConfig = response.data
          if (that.enterpriseConfig) {
            if (that.enterpriseConfig.orderStatTime) {
              const times = that.enterpriseConfig.orderStatTime.split(':')
              that.groupBuyCutOffOrderTimeForm.statTime = times[0] + ':' + times[1] + ':' + times[2]
              // that.groupBuyCutOffOrderTimeForm.statTime.setHours(times[0])
              // that.groupBuyCutOffOrderTimeForm.statTime.setMinutes(times[1])
              // that.groupBuyCutOffOrderTimeForm.statTime.setSeconds(times[2])
            }
            if (that.enterpriseConfig.orderStatTimeWeekCycle) {
              that.groupBuyCutOffOrderTimeForm.orderStatTimeWeekCycle = that.enterpriseConfig
                .orderStatTimeWeekCycle.split(',')
            }
          }
        })
      },
      saveGroupBuyCutOffOrderTimeConfig() {
        const that = this
        that.$refs['groupBuyCutOffOrderTimeForm'].validate(valid => {
          if (valid) {
            if (!that.enterpriseConfig) {
              that.enterpriseConfig = {}
            }
            const params = {}
            params.orderStatTimeWeekCycle = that.groupBuyCutOffOrderTimeForm
              .orderStatTimeWeekCycle.join(',')
            params.orderStatTime = that.groupBuyCutOffOrderTimeForm.statTime
            params.enterpriseId = that.getEnterpriseId()
            saveOrderStatTimeInfo(params).then(response => {
              if (response.isError) return
              that.isShowSetGroupBuyCutOffOrderTimeDialog = false
              that.msgSuccess('保存成功')
            })
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .bgc-default {
    .flex-left {
      display: flex;
      justify-content: flex-start;
      align-items: center;
    }

    .title-row {
      margin-top: 44px;
      margin-bottom: 25px;
    }

    .panel {
      width: 300px;
      height: 150px;
      border-radius: 4px;
      background: white;
      margin-right: 20px;
      box-shadow: 0px 3px 19px 0px rgba(154, 154, 154, 0.18);

      .line-x {
        line-height: 1.3;
      }

      img {
        border-radius: 50%;
      }

      .img-1 {
        background: #dffffd;
      }

      .img-2 {
        background: #eaf4ff;
      }

      .manage-row {
        margin: 0 24px;
        border-top: 1px dashed #E5E5E5;

        .createBtn {
          height: 32px;
          line-height: 32px;
          border-radius: 4px;
          color: white;
          padding: 0 26px;
          font-size: 14px;

          &:hover {
            cursor: pointer;
          }
        }

        .seckillBtn {
          background-color: #46DEC6;
        }

        .postBtn {
          background-color: #409EFF;
        }
      }
    }
  }

  .mission-type {
    padding: 35px 38px;
    min-width: 150px;
    border: 1px solid #dcdcdc;
    border-radius: 8px;
    margin: 25px 40px;
    cursor: pointer;
    text-align: center;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  }

  .flex-cag-box {
    padding: 0px 0px 20px 70px;

    .mission-type:nth-child(4n) {
      margin-right: 0px;
    }
  }

  .next-step-btn {
    padding: 13px 35px;
    font-size: 18px;
  }

  .sel-mission-type {
    background-color: #409eff;
    color: #fff;
  }

  .budget-el-select {
    padding-top: 10px;
    padding-left: 50px;
  }
</style>
